<template>
  <BaseTable
    max-fill
    :loading="loading"
    :data-source="dataSource"
    column-code="000117"
    :extra-height="64"
    :scroll="{ x: 2000 }"
    :pagination="false"
    :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
  >
    <template #bodyCell="{ column, index, record }">
      <template v-if="column.dataIndex === 'mc'">
        <EditCell title="处置类型">
          <SelectMedicine v-model:value="record.sfxm" type="处置类型" :auto-focus="record.isNew && index > 0" @select="onSelect($event, record)" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'sl'">
        <EditCell title="数量">
          <BaseInput
            v-model:value="record.sl"
            v-input:int
            v-input-selection
            :auto-focus="record.isNew && focusCell === record.key + '数量'"
            placeholder="请输入"
            :suffix="record.sfxm?.dw"
            @keydown.enter="saveNewRows(true)"
            @blur="editRow(record)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'partName'">
        <EditCell title="部位">
          <!-- <a-select
            v-model:value="record.partCode"
            :max-tag-count="1"
            :max-tag-text-length="3"
            placeholder="请选择"
            :options="partData"
            mode="multiple"
            allow-clear
            @change="editRow(record)"
          /> -->
          <SelectPartTags
            :value="record"
            multiple
            allow-clear
            show-new
            :input-or-textarea="true"
            type="部位"
            @select="(event) => onSelectPart(record, event)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'scName'">
        <EditCell title="时长">
          <SelectItem
            v-model:value="record.sc"
            type="zy_duration_type"
            trigger="init"
            style-class="w-full"
            placeholder="请选择"
            @change="
              (_, $event) => {
                record.sc = $event.value
                record.scName = $event.label
                editRow(record)
              }
            "
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'fyff'">
        <EditCell title="用法">
          <SelectTable :value="record.yf?.fyff" :search-params="{ isMedicine: 0 }" :table-width="360" type="用法" @select="onSelectWays($event, record)" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'yssm'">
        <EditCell title="处置说明">
          <a-input v-model:value="record.yssm" v-input-selection placeholder="请输入" @blur="editRow(record)" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'apportionmentAllowed'">
        <a-switch :checked="record.apportionmentAllowed" :disabled="record.isNew" :un-checked-value="0" :checked-value="1" @click="onSwitch(record)" />
      </template>
      <template v-else-if="column.dataIndex === 'action'">
        <BaseButton confirm-text="确定作废?" type="link" size="small" danger @click="onDelete(record)">作废</BaseButton>
      </template>
    </template>
    <template #footer>
      <div class="text-center sticky bottom-0">
        <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" :disabled="!suitStore.currentSuit.tcid" @click="addRow()"> 新增一行 </a-button>
        <a-button type="primary" :icon="h(SaveOutlined)" :disabled="!isHaveNewRow" @click="saveNewRows()"> 保存 </a-button>
      </div>
    </template>
  </BaseTable>
</template>
<script setup>
import { ref, computed, h, watch } from 'vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import BaseTable from '@/components/BaseTable'
import BaseButton from '@/components/BaseButton'
import EditCell from '@/components/EditCell'
import { post } from '@/utils/request'
import useSuitStore from '../store'

const emit = defineEmits(['success'])
const suitStore = useSuitStore()
const loading = ref(false)
const focusCell = ref(null)
const dataSource = ref([])
const defaultRow = { isNew: true, cfbh: 1, apportionmentAllowed: 1 }
const isHaveNewRow = computed(() => {
  return dataSource.value.some((item) => item.isNew)
})

const saveNewRows = async (addNew) => {
  const newRows = dataSource.value.filter((item) => item.isNew)
  newRows.forEach((item) => {
    fetchSave(item, addNew)
  })
}
const onSelectPart = (record, val) => {
  record.partCode = val?.partCode || []
  record.partName = val?.partName || ''
  editRow(record)
}
const editRow = (row) => {
  !row.isNew && fetchSave(row)
}
const fetchSave = async (row, addNew) => {
  if (row.sfxm && row.sl) {
    const { code, msg } = await post('/outp/template/doAddClinicalOrderPackageItem', { tcid: suitStore.currentSuit.tcid, ...row })
    if (code !== 0) return message.error(msg || '操作失败')
    message.destroy()
    message.success(row.isNew ? '新增成功' : '修改成功')
    getData(addNew)
    emit('success')
  } else {
    message.destroy()
    message.error('请填写完整信息')
  }
}
//获取数据
const getData = async (addNew) => {
  loading.value = true
  const { data, code } = await post('/outp/template/getClinicalOrderPackageItemList', { tcid: suitStore.currentSuit.tcid, czcf: 2 })
  loading.value = false
  if (code !== 0) return
  if (data.length > 0) {
    dataSource.value = data.map((item) => {
      return { ...item, key: item.id }
    })
    addNew && addRow()
  } else {
    dataSource.value = [{ key: 'row-0', ...defaultRow }]
  }
}
watch(
  () => suitStore.currentSuit.tcid,
  (val) => {
    val ? getData() : (dataSource.value = [])
  }
)

const onSelect = (selected, record) => {
  record.lbmc = selected.lbmc
  record.mc = selected.mc
  record.sfxm = selected
  record.sl = 1
  record.dw = selected.dw
  focusCell.value = record.key + '数量'
  editRow(record)
}

const onDelete = async (row) => {
  if (row.id) {
    const { code, msg } = await post('/outp/template/doDelClinicalOrderPackageItem', {
      bh: row.bh,
      tcid: suitStore.currentSuit.tcid,
      cjr: suitStore.currentSuit.cjr
    })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success('删除成功')
    getData()
    emit('success')
  } else {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  }
}
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  dataSource.value.push({ key, ...defaultRow })
}
const onSwitch = async (row) => {
  const { code, msg } = await post('/outp/template/allocationAllowed', {
    apportionmentAllowed: row.apportionmentAllowed ? 0 : 1,
    id: row.id
  })
  if (code !== 0) return message.error(msg || '操作失败')
  getData()
}
//选用法
const onSelectWays = (selected, row) => {
  row.yf = selected
  editRow(row)
}
//自动选中内容
</script>
<style lang="less" scoped></style>
